var loginState = false;
var flag = false;

(function () {
    // 加载登录模块视图
    const loginViewStr = `
        <div id="login-wrap">
            <form action="javascript:;">
                <table>
                    <caption>登录游戏</caption>
                    <tr>
                        <td>账号：</td>
                        <td><input type="text" name="username"></td>
                        <td>
                            <div class="deleteInput">×</div>
                        </td>
                    </tr>
                    <tr>
                        <td>密码：</td>
                        <td><input type="password" name="password"></td>
                        <td>
                            <div class="deleteInput">×</div>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="3">
                            <label>记住密码：<input type="checkbox" checked></label>
                            <input type="submit" value="登录">
                        </td>
                    </tr>
                </table>
                <button id="registerBtn">注册</button>
            </form>
        </div>
    `;

    // 注册模块视图
    const registerViewStr = `
        <div id="register-wrap">
            <form action="javascript:;">
                <table>
                    <caption>注册游戏</caption>
                    <tr>
                        <td>账号：</td>
                        <td><input type="text" name="username"></td>
                        <td>
                            <div class="deleteInput">×</div>
                        </td>
                    </tr>
                    <tr>
                        <td>密码：</td>
                        <td><input type="password" name="password"></td>
                        <td>
                            <div class="deleteInput">×</div>
                        </td>
                    </tr>
                    <tr>
                        <td>确认密码：</td>
                        <td><input type="password" name="password1"></td>
                        <td>
                            <div class="deleteInput">×</div>
                        </td>
                    </tr>
                    <tr>
                        <td>验证码：</td>
                        <td colspan="2">
                            <img class="yzm" src="">
                            <input class="yzm-input">
                            <button class="hyz">换一张</button>
                        </td>
                    </tr>
                    <tr>
                        <td></td>
                        <td>
                            <input type="submit" value="注册">
                            <input type="reset">
                            <button id="loginBtn">登录</button>
                        </td>
                    </tr>
                </table>
            </form>
        </div>
    `;

    //添加登录模块视图到游戏前景
    var loginDiv = document.createElement('div');
    loginDiv.innerHTML = loginViewStr;
    loginDiv = loginDiv.children[0];

    //自动填写账号和密码
    if (localStorage) {
        usernameLS = localStorage.getItem("username");
        passwordLS = localStorage.getItem("password");

        if (usernameLS == null) {
            usernameLS = '';
        };
        if (passwordLS == null) {
            passwordLS = '';
        };

        loginDiv.querySelector('input[type="text"]').value = usernameLS;
        loginDiv.querySelector('input[type="password"]').value = passwordLS;
    };


    //登录模块js代码
    var loginWrap = loginDiv;

    //输入框获得焦点上移
    loginWrap.querySelector('input[type="text"]').onfocus = function () {
        loginWrap.style.top = '22%';
    }
    loginWrap.querySelector('input[type="text"]').onblur = function () {
        loginWrap.style.top = '50%';
    }
    loginWrap.querySelector('input[type="password"]').onfocus = function () {
        loginWrap.style.top = '22%';
    }
    loginWrap.querySelector('input[type="password"]').onblur = function () {
        loginWrap.style.top = '50%';
    }

    var deleteInputs = loginWrap.querySelectorAll('.deleteInput');

    deleteInputs[0].onclick = function () {
        loginWrap.querySelector('input[type="text"]').value = '';
    }
    deleteInputs[1].onclick = function () {
        loginWrap.querySelector('input[type="password"]').value = '';
    }

    //点击了登录按钮事件
    var loginBtnSubmit = loginWrap.querySelector('input[type="submit"]');
    loginBtnSubmit.onclick = function () {

        var usernameVal = loginWrap.querySelector('input[type="text"]').value;
        var passwordVal = loginWrap.querySelector('input[type="password"]').value;

        if (usernameVal == "") {
            popMessage('请输入账号或者注册账号');
            return;
        }
        if (usernameVal.trim().length > 15) {
            popMessage('账号长度在1-15位之间');
            return;
        }
        if (passwordVal == "") {
            popMessage('请输入密码');
            return;
        }
        if (passwordVal.length < 6 || passwordVal.length > 20) {
            popMessage('密码长度在6-20位之间');
            return;
        }

        // 登录验证
        $.ajax({
            "url": "sql.asp",
            "type": "post",
            "data": {
                action: 'login',
                username: usernameVal,
                password: passwordVal
            },
            "dataType": "text",
            "success": function (data) {
                var jsonData = JSON.parse(data)
                if (jsonData.state === 'ok') {
                    //登录成功

                    //把账号和密码保存到localStorage中
                    if (localStorage) {
                        if (loginWrap.querySelector('input[type="checkbox"]').checked) {
                            localStorage.setItem('username', usernameVal);
                            localStorage.setItem('password', passwordVal);
                        } else {
                            localStorage.setItem('username', '');
                            localStorage.setItem('password', '');
                        }
                    }

                    //处理数据
                    gameDatas = jsonData;
                    console.log(gameDatas);

                    ID = gameDatas.ID;
                    //初始化主界面数据
                    if (loginState === false) {
                        loginState = true;
                        popDialog('<h3 style="text-align: center">公告</h3><br><div style="text-indent: 2em;">' + gameDatas.public + '</div>', 1, function () {
                            initMainViewDatas();
                        });
                    }
                } else if (jsonData.state === 'error') {
                    popMessage(jsonData.msg);
                } else {
                    popMessage(ajaxDataError);
                }
            },
            "error": function () {
                popMessage(ajaxError);
            }
        });
    };

    //返回登录视图dom
    loginView = loginDiv;

    //点击了注册按钮
    var registerBtn = loginDiv.querySelector('#registerBtn');
    registerBtn.onclick = function () {
        if (flag) {
            return;
        }
        flag = true;
        gamescene.removeChild(gamescene.lastElementChild);
        var registerDiv = document.createElement('div');
        registerDiv.innerHTML = registerViewStr;
        registerDiv = registerDiv.children[0];
        gamescene.appendChild(registerDiv);

        var loginBtn = gamescene.querySelector('#loginBtn');
        loginBtn.onclick = function () {
            if (!flag) {
                return;
            }
            flag = false;
            gamescene.removeChild(gamescene.lastElementChild);
            gamescene.appendChild(loginDiv);
        }

        var deleteInputReg = registerDiv.querySelectorAll('.deleteInput');
        deleteInputReg.forEach(item => {
            item.onclick = function () {
                item.parentNode.previousElementSibling.children[0].value = '';
            }
        })

        //获得焦点和失去焦点
        registerDiv.querySelector('input[name="username"]').onfocus =
            registerDiv.querySelector('input[name="password"]').onfocus =
            registerDiv.querySelector('input[name="password1"]').onfocus =
            registerDiv.querySelector('.yzm-input').onfocus = function () {
                registerDiv.style.top = '20%';
            }
        registerDiv.querySelector('input[name="username"]').onblur =
            registerDiv.querySelector('input[name="password"]').onblur =
            registerDiv.querySelector('input[name="password1"]').onblur =
            registerDiv.querySelector('.yzm-input').onblur = function () {
                registerDiv.style.top = '50%';
            }

        // 请求验证码
        function getCode() {
            $.ajax({
                "url": "sql.asp",
                "type": "post",
                "data": {
                    action: 'getCode'
                },
                "dataType": "text",
                "success": function (data) {
                    var jsonData = JSON.parse(data)
                    if (jsonData.state === 'ok') {
                        registerDiv.querySelector('.yzm').src = "images/code/" + jsonData.code + ".png";
                    } else if (jsonData.state === 'error') {
                        popMessage(jsonData.msg);
                    } else {
                        popMessage(ajaxDataError);
                    }
                },
                "error": function () {
                    popMessage(ajaxError);
                }
            })
        }

        //getCode();

        registerDiv.querySelector('.hyz').onclick = function () {
            getCode();
        }

        registerDiv.querySelector('input[type="submit"]').onclick = function () {
            var usernameRegVal = registerDiv.querySelector('input[name="username"]').value.trim();
            var passwordRegVal = registerDiv.querySelector('input[name="password"]').value;
            var passwordRegVal1 = registerDiv.querySelector('input[name="password1"]').value;
            var yzmContent = registerDiv.querySelector('.yzm-input').value.trim();

            if (usernameRegVal.length < 4 || usernameRegVal.length > 12) {
                popMessage('账号的长度在必须4-12之间');
                return;
            }
            if (passwordRegVal.length < 6 || passwordRegVal.length > 15) {
                popMessage('密码的长度在必须6-15之间');
                return;
            }
            if (passwordRegVal1.length < 6 || passwordRegVal1.length > 15) {
                popMessage('确认密码的长度必须在6-15之间');
                return;
            }
            if (passwordRegVal !== passwordRegVal1) {
                popMessage('两次输入的密码不一致');
                return;
            }
            if (yzmContent.length === 0) {
                popMessage('请输入验证码');
                return;
            }

            // 注册游戏
            $.ajax({
                "url": "sql.asp",
                "type": "post",
                "data": {
                    action: 'register',
                    username: usernameRegVal,
                    password: passwordRegVal,
                    yzm: yzmContent
                },
                "dataType": "text",
                "success": function (data) {
                    var jsonData = JSON.parse(data)
                    if (jsonData.state === 'ok') {
                        //注册成功
                        popDialog('注册成功，您的账号为：' + usernameRegVal + '，密码为：' + passwordRegVal + '，您可以截图保存，以免遗忘。', 1, function () {
                            loginBtn.onclick();
                        });
                    } else if (jsonData.state === 'error') {
                        popMessage(jsonData.msg);
                        getCode();
                    } else {
                        popMessage(ajaxDataError);
                    }
                },
                "error": function () {
                    popMessage(ajaxError);
                }
            });
        }
    }
})();
